<template>
  <div class="page-box">
    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <i class="el-icon-tickets"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ statistics.total || 0 }}</div>
                <div class="stat-label">总优惠券数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon available">
                <i class="el-icon-check"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ statistics.available || 0 }}</div>
                <div class="stat-label">可用优惠券</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon distributed">
                <i class="el-icon-share"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ statistics.distributed || 0 }}</div>
                <div class="stat-label">已分发</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon rate">
                <i class="el-icon-pie-chart"></i>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ statistics.distribution_rate || 0 }}%</div>
                <div class="stat-label">分发率</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 优惠券列表 -->
    <universal-table
      :columns="columns"
      :fetch-data="fetchTableData"
      permission-prefix="sys:nfc_merchant_coupon"
      :show-selection="true"
      :show-index="true"
      :export-file-name="'商户优惠券'"
      :init-search-form="{}"
      @batch-action="handleBatchAction"
      @selection-change="handleSelectionChange"
      @status-change="handleStatusChange"
      @delete="handleDelete"
      ref="table">

      <!-- 搜索区域扩展 -->
      <template #searchExtend>
        <el-form-item prop="merchant_id">
          <el-select
            v-model="searchForm.merchant_id"
            placeholder="选择商户"
            clearable
            filterable
            @change="handleMerchantChange">
            <el-option
              v-for="merchant in merchantList"
              :key="merchant.id"
              :label="merchant.merchant_name"
              :value="merchant.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="status">
          <el-select v-model="searchForm.status" placeholder="状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="is_distributed">
          <el-select v-model="searchForm.is_distributed" placeholder="分发状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="未分发" value="0"></el-option>
            <el-option label="已分发" value="1"></el-option>
          </el-select>
        </el-form-item>

        <!-- 批量操作按钮区域 -->
        <el-form-item>
          <el-button type="primary" icon="el-icon-upload" @click="showUploadDialog">
            批量上传
          </el-button>
          <el-button type="info" icon="el-icon-download" @click="downloadTemplate">
            下载模版
          </el-button>
          <el-button type="default" icon="el-icon-document" @click="exportCoupons">
            导出CSV
          </el-button>
          <el-button type="success" icon="el-icon-check" @click="handleBatchEnable" :disabled="!hasSelection">
            批量启用
          </el-button>
          <el-button type="warning" icon="el-icon-close" @click="handleBatchDisable" :disabled="!hasSelection">
            批量禁用
          </el-button>
          <el-button type="danger" icon="el-icon-delete" @click="handleBatchDeleteFromSearch" :disabled="!hasSelection">
            批量删除
          </el-button>
        </el-form-item>
      </template>
    </universal-table>

    <!-- 批量上传对话框 -->
    <el-dialog title="批量上传优惠券" :visible.sync="uploadDialogVisible" width="600px">
      <div class="upload-content">
        <!-- 上传说明 -->
        <el-alert
          title="上传说明"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;">
          <template slot>
            <div>
              <p>1. 支持CSV和TXT格式文件</p>
              <p>2. 文件格式：优惠券名称,优惠券代码,描述</p>
              <p>3. 第一行如果是标题行会自动跳过</p>
              <p>4. 优惠券代码不能重复</p>
            </div>
          </template>
        </el-alert>

        <!-- 文件上传 -->
        <el-upload
          ref="upload"
          class="upload-demo"
          drag
          :action="uploadAction"
          :headers="uploadHeaders"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          :before-upload="beforeUpload"
          :file-list="uploadFileList"
          :limit="1"
          :auto-upload="false">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传csv/txt文件，且不超过2MB</div>
        </el-upload>

        <!-- 上传结果 -->
        <div v-if="uploadResult" class="upload-result">
          <el-alert
            :title="`上传结果：成功 ${uploadResult.success_count} 条，失败 ${uploadResult.fail_count} 条`"
            :type="uploadResult.fail_count > 0 ? 'warning' : 'success'"
            :closable="false">
          </el-alert>
          <div v-if="uploadResult.errors && uploadResult.errors.length > 0" class="upload-errors">
            <p><strong>错误详情：</strong></p>
            <ul>
              <li v-for="(error, index) in uploadResult.errors" :key="index">{{ error }}</li>
            </ul>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpload" :loading="uploading">确定上传</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import UniversalTable from "@/components/TableComponent.vue";
import {
  getCouponList,
  getCouponStatistics,
  updateCouponStatus,
  deleteCoupon,
  batchUpdateCouponStatus,
  batchDeleteCoupons,
  downloadCouponTemplate,
  exportCoupons as exportCouponsApi
} from '@/api/merchant-coupon';

export default {
  name: 'MerchantCouponIndex',
  components: {
    UniversalTable
  },
  data() {
    return {
      // 统计数据
      statistics: {
        total: 0,
        available: 0,
        distributed: 0,
        distribution_rate: 0
      },

      // 表格配置
      columns: [
        {
          prop: "coupon_name",
          label: "优惠券名称",
          minWidth: 150
        },
        {
          prop: "coupon_code",
          label: "优惠券代码",
          minWidth: 120
        },
        {
          prop: "description",
          label: "描述",
          minWidth: 200,
          showOverflowTooltip: true
        },
        {
          prop: "is_distributed",
          label: "分发状态",
          tag: true,
          tagConfig: {
            0: { type: 'info', text: '未分发' },
            1: { type: 'success', text: '已分发' }
          }
        },
        {
          prop: "status",
          label: "状态",
          tag: true,
          tagConfig: {
            0: { type: 'danger', text: '禁用' },
            1: { type: 'success', text: '启用' }
          }
        },
        {
          prop: "create_time",
          label: "创建时间",
          minWidth: 150
        }
      ],

      // 搜索表单
      searchForm: {
        merchant_id: '',
        status: '',
        is_distributed: ''
      },

      // 商户列表
      merchantList: [],

      // 上传相关
      uploadDialogVisible: false,
      uploading: false,
      uploadFileList: [],
      uploadResult: null,
      uploadAction: '', // 将在mounted中设置
      uploadHeaders: {},

      // 选择相关
      hasSelection: false
    };
  },

  mounted() {
    this.loadMerchantList();
    this.loadStatistics();
    this.setupUploadConfig();
  },

  methods: {
    // 加载商户列表
    async loadMerchantList() {
      try {
        // 这里需要调用获取商户列表的API
        // 临时使用NFC API中的商户列表
        const response = await this.$http.get('nfc/campaigns/merchants');
        const result = response.data; // 使用axios-config返回的完整响应对象
        if (result.code === 200) {
          this.merchantList = result.data || [];
        }
      } catch (error) {
        console.error('加载商户列表失败:', error);
        this.$message.error('加载商户列表失败');
      }
    },

    // 加载统计数据
    async loadStatistics() {
      try {
        const merchantId = this.searchForm.merchant_id || null;
        const result = await getCouponStatistics(merchantId);
        if (result.code === 200) {
          this.statistics = result.data;
        }
      } catch (error) {
        console.error('加载统计数据失败:', error);
      }
    },

    // 商户选择变化
    handleMerchantChange() {
      // 重新加载数据
      this.loadStatistics();
      if (this.$refs.table) {
        this.$refs.table.refresh();
      }
    },

    // 设置上传配置
    setupUploadConfig() {
      const merchantId = this.searchForm.merchant_id;
      const baseUrl = this.$httpRequest.instance.defaults.baseURL || process.env.VUE_APP_API_BASE_URL;
      this.uploadAction = merchantId ?
        `${baseUrl}/merchant/coupons/batch-upload?merchant_id=${merchantId}` :
        `${baseUrl}/merchant/coupons/batch-upload`;

      // 获取当前token
      const token = this.$store.getters.token;
      console.log('Token获取结果:', token); // 调试日志
      this.uploadHeaders = token ? {
        'Authorization': token
      } : {};
      console.log('上传配置:', {
        uploadAction: this.uploadAction,
        uploadHeaders: this.uploadHeaders
      }); // 调试日志
    },

    // 显示上传对话框前检查
    showUploadDialog() {
      if (!this.searchForm.merchant_id) {
        this.$message.warning('请先选择要上传优惠券的商户');
        return;
      }
      // 重新设置上传配置（包含merchant_id）
      this.setupUploadConfig();
      this.uploadDialogVisible = true;
      this.uploadResult = null;
      this.uploadFileList = [];
    },

    // 文件选择变化
    handleFileChange(file, fileList) {
      this.uploadFileList = fileList;
      console.log('文件选择变化:', {
        fileList: fileList,
        fileCount: fileList.length,
        currentFile: file
      });
    },

    // 文件移除
    handleFileRemove(file, fileList) {
      this.uploadFileList = fileList;
      console.log('文件移除:', {
        removedFile: file,
        remainingList: fileList
      });
    },

    // 获取表格数据
    async fetchTableData(params = {}) {
      const postData = Object.assign({}, params, this.searchForm);

      // 如果没有选择商户，提示用户选择
      if (!postData.merchant_id) {
        this.$message.warning('请先选择要查看的商户');
        return { list: [], total: 0 };
      }

      try {
        const result = await getCouponList(postData);
        console.log('获取优惠券列表:', result);

        // 返回TableComponent期望的数据格式
        if (result.code === 200) {
          return {
            list: result.data.list || [],
            total: result.data.total || 0
          };
        } else {
          this.$message.error(result.message || '获取数据失败');
          return { list: [], total: 0 };
        }
      } catch (error) {
        this.$message.error(error.message || '获取数据失败');
        return { list: [], total: 0 };
      }
    },

    // 上传前验证
    beforeUpload(file) {
      const allowedExtensions = ['csv', 'txt'];
      const extension = file.name.split('.').pop().toLowerCase();

      if (!allowedExtensions.includes(extension)) {
        this.$message.error('只能上传CSV或TXT格式文件！');
        return false;
      }

      if (file.size > 2 * 1024 * 1024) {
        this.$message.error('文件大小不能超过2MB！');
        return false;
      }

      return true;
    },

    // 执行上传
    async submitUpload() {
      // 调试信息
      console.log('提交上传 - 当前状态:', {
        uploadFileList: this.uploadFileList,
        uploadFileListLength: this.uploadFileList.length,
        uploadRef: this.$refs.upload,
        uploadFiles: this.$refs.upload ? this.$refs.upload.uploadFiles : null
      });

      // 多种方式检查文件是否存在
      const hasFile = this.uploadFileList.length > 0 ||
                     (this.$refs.upload && this.$refs.upload.uploadFiles && this.$refs.upload.uploadFiles.length > 0);

      if (!hasFile) {
        this.$message.warning('请选择要上传的文件');
        return;
      }

      this.uploading = true;
      this.$refs.upload.submit();
    },

    // 上传成功回调
    handleUploadSuccess(response) {
      this.uploading = false;
      console.log('上传响应:', response);

      if (response.code === 200) {
        this.uploadResult = response.data;
        this.$message.success('上传完成');
        this.$refs.table.refresh(); // 刷新表格
        this.loadStatistics(); // 刷新统计
      } else {
        this.$message.error(response.message || '上传失败');
      }
    },

    // 上传失败回调
    handleUploadError(err) {
      this.uploading = false;
      console.error('上传失败:', err);
      this.$message.error('上传失败，请稍后重试');
    },

    // 状态变更
    async handleStatusChange(row) {
      try {
        const result = await updateCouponStatus(row.id, row.status, this.searchForm.merchant_id);
        if (result.code === 200) {
          this.$message.success('状态更新成功');
          this.$refs.table.refresh();
          this.loadStatistics();
        } else {
          this.$message.error(result.message || '状态更新失败');
        }
      } catch (error) {
        this.$message.error(error.message || '状态更新失败');
      }
    },

    // 删除
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除这个优惠券吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        const result = await deleteCoupon(row.id, this.searchForm.merchant_id);
        if (result.code === 200) {
          this.$message.success('删除成功');
          this.$refs.table.refresh();
          this.loadStatistics();
        } else {
          this.$message.error(result.message || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || '删除失败');
        }
      }
    },

    // 选择变化
    handleSelectionChange(selection) {
      this.hasSelection = selection.length > 0;
    },

    // 批量操作
    handleBatchAction(action, selectedRows) {
      this.hasSelection = selectedRows.length > 0;

      if (action === 'delete') {
        this.handleBatchDelete(selectedRows);
      }
    },

    // 批量启用
    async handleBatchEnable() {
      const selectedRows = this.$refs.table ? this.$refs.table.getSelection() : [];
      if (selectedRows.length === 0) {
        this.$message.warning('请先选择要启用的优惠券');
        return;
      }

      try {
        const ids = selectedRows.map(row => row.id);
        const result = await batchUpdateCouponStatus(ids, 1, this.searchForm.merchant_id);
        if (result.code === 200) {
          this.$message.success('批量启用成功');
          this.$refs.table.refresh();
          this.loadStatistics();
        } else {
          this.$message.error(result.message || '批量启用失败');
        }
      } catch (error) {
        this.$message.error(error.message || '批量启用失败');
      }
    },

    // 批量禁用
    async handleBatchDisable() {
      const selectedRows = this.$refs.table ? this.$refs.table.getSelection() : [];
      if (selectedRows.length === 0) {
        this.$message.warning('请先选择要禁用的优惠券');
        return;
      }

      try {
        const ids = selectedRows.map(row => row.id);
        const result = await batchUpdateCouponStatus(ids, 0, this.searchForm.merchant_id);
        if (result.code === 200) {
          this.$message.success('批量禁用成功');
          this.$refs.table.refresh();
          this.loadStatistics();
        } else {
          this.$message.error(result.message || '批量禁用失败');
        }
      } catch (error) {
        this.$message.error(error.message || '批量禁用失败');
      }
    },

    // 批量删除
    async handleBatchDelete(selectedRows) {
      if (selectedRows.length === 0) {
        this.$message.warning('请先选择要删除的优惠券');
        return;
      }

      // 检查是否有已分发的优惠券
      const distributedCoupons = selectedRows.filter(row => row.is_distributed === 1);
      if (distributedCoupons.length > 0) {
        this.$message.error('已分发的优惠券不能删除');
        return;
      }

      try {
        await this.$confirm(`确认删除选中的 ${selectedRows.length} 个优惠券吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        const ids = selectedRows.map(row => row.id);
        const result = await batchDeleteCoupons(ids, this.searchForm.merchant_id);
        if (result.code === 200) {
          this.$message.success('批量删除成功');
          this.$refs.table.refresh();
          this.loadStatistics();
        } else {
          this.$message.error(result.message || '批量删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || '批量删除失败');
        }
      }
    },

    // 批量删除从搜索区域
    handleBatchDeleteFromSearch() {
      const selectedRows = this.$refs.table ? this.$refs.table.getSelection() : [];
      if (selectedRows.length === 0) {
        this.$message.warning('请先选择要删除的优惠券');
        return;
      }

      this.handleBatchDelete(selectedRows);
    },

    // 下载模版
    async downloadTemplate() {
      try {
        this.$message.info('正在下载模版...');
        const response = await downloadCouponTemplate();

        // 创建下载链接
        const blob = new Blob([response], { type: 'text/csv;charset=utf-8' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = 'coupon_upload_template.csv';

        // 触发下载
        document.body.appendChild(link);
        link.click();

        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        this.$message.success('模版下载成功');
      } catch (error) {
        console.error('下载模版失败:', error);
        this.$message.error('下载模版失败，请稍后重试');
      }
    },

    // 导出优惠券数据
    async exportCoupons() {
      if (!this.searchForm.merchant_id) {
        this.$message.warning('请先选择要导出的商户');
        return;
      }

      try {
        this.$message.info('正在生成CSV文件...');

        // 构建导出参数
        const exportParams = {
          merchant_id: this.searchForm.merchant_id,
          status: this.searchForm.status,
          is_distributed: this.searchForm.is_distributed
        };

        const response = await exportCouponsApi(exportParams);

        // 创建下载链接
        const blob = new Blob([response], { type: 'text/csv;charset=utf-8' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;

        // 生成文件名
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
        link.download = `优惠券数据_${timestamp}.csv`;

        // 触发下载
        document.body.appendChild(link);
        link.click();

        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        this.$message.success('CSV文件导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败，请稍后重试');
      }
    }
  }
};
</script>

<style scoped>
.page-box {
  padding: 20px;
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  overflow: hidden;
  height: 120px;
}

.stat-card .el-card__body {
  padding: 20px;
  height: 100%;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: #fff;
}

.stat-info {
  flex: 1;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.available {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.distributed {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.rate {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.upload-content {
  max-height: 500px;
  overflow-y: auto;
}

.upload-result {
  margin-top: 20px;
}

.upload-errors {
  margin-top: 10px;
  max-height: 200px;
  overflow-y: auto;
  background: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
}

.upload-errors ul {
  margin: 5px 0;
  padding-left: 20px;
}

.upload-errors li {
  color: #e74c3c;
  margin-bottom: 3px;
}

/* 批量操作按钮样式 */
.search-area .el-form-item:last-child {
  margin-bottom: 0;
}

.search-area .el-form-item:last-child .el-button {
  margin-right: 8px;
}

.search-area .el-form-item:last-child .el-button:last-child {
  margin-right: 0;
}
</style>
